const express = require('express')
const app = express()
const cors = require('cors')
const userRouter = require('./router/user')
const userinfoRouter = require('./router/userinfo')
const artCateRouter = require('./router/art_cate')
const articleRouter=require('./router/article')
const joi = require('joi')
const {
  expressjwt
} = require('express-jwt')
const {
  jwtSecretKey
} = require('./secretkey/config')

// 解析 application/x-www-from-urlencoded数据
app.use(express.urlencoded({
  extended: false
}))
// 跨域
app.use(cors())
// 挂载封装的全局函数
app.use((req, res, next) => {
  res.cc = function (err, status = 1) {
    res.send({
      status,
      message: err instanceof Error ? err.message : err
    })
  }
  next()
})
// 挂载解析token的中间件
app.use(expressjwt({
  secret: jwtSecretKey,
  algorithms: ['HS256']
}).unless({
  path: [/^\/api/]
}))
// 挂载路由
// 登录与注册
app.use('/api', userRouter)
// 获取个人信息
app.use('/my', userinfoRouter)
// 获取文章分类
app.use('/my/article', artCateRouter)
app.use('/my/article', articleRouter)
// 错误级别中间件捕获错误 
app.use((err, req, res, next) => {
  // 验证失败
  if (err instanceof joi.ValidationError) return res.cc(err)
  // 身份认证失败
  if (err.name === 'UnauthorizedError') return res.cc('身份认证失败')
})
app.listen(80, () => {
  console.log('服务器启动成功');
})